package com.situ.web.service.impl;

import java.util.List;

import com.situ.web.dao.IStudentDao;
import com.situ.web.dao.impl.StudentDaoImpl;
import com.situ.web.entity.PageBean;
import com.situ.web.entity.Student;
import com.situ.web.exception.NameRepeatException;
import com.situ.web.service.IStudentService;

public class StudentServiceImpl implements IStudentService{
	//private StudentDaoImpl studentDao = new StudentDaoImpl();
	private IStudentDao studentDao = new StudentDaoImpl();
	
	@Override
	public boolean register(Student student) throws NameRepeatException {
		//1、判读这个学生还不是存在
		if (studentDao.checkName(student.getName())) {
			//System.out.println("该用户名已经存在");
			//return false;
			throw new NameRepeatException("该用户名已经存在");
		} else {//2 、这个用户名不存在
			//return studentDao.insert(student) > 0 ? true : false;
			int result = studentDao.insert(student);
			if (result > 0) {
				return true;
			} else {
				return false;
			}
		}
	}

	@Override
	public List<Student> findAll() {
		return studentDao.findAll();
	}

	@Override
	public boolean deleteById(int id) {
		return studentDao.deleteById(id) > 0 ? true : false;
		/*int count = studentDao.deleteById(id);
		if (count > 0) {
			return true;
		} else {
			return false;
		}*/
	}

	@Override
	public Student findById(int id) {
		return studentDao.findById(id);
	}

	@Override
	public boolean updateById(Student student) {
		return studentDao.updateById(student) > 0 ? true : false;
	}

	@Override
	public PageBean getPageBean(Integer pageNo, Integer pageSize) {
		PageBean pageBean = new PageBean();
		//当前是第几页
		pageBean.setPageNo(pageNo);
		//一页有多少条数据
		pageBean.setPageSize(pageSize);
		//一共有多少页
		int totalCount = studentDao.getTotalCount();//查询一共有多少条数据
		//总数量    每页数量   总页数
		// 10     3       4       10/3=3...1
		// 11     3       4       11/3=3...2
		// 12     3       4       11/3=4
		// 13     3       5       11/3=4...1
		int totalPage = (int) Math.ceil((double)totalCount / pageSize);
		pageBean.setTotalPage(totalPage);
		//当前页数据  limit   (pageNo-1)*3, pageSize
		int offset = (pageNo - 1) * pageSize;
		List<Student> list = studentDao.pageList(offset, pageSize);
		pageBean.setList(list);
		
		return pageBean;
	}
	
	public static void main(String[] args) {
		int totalCount = 28;
		int pageSize = 3;
		//9.33333
		System.out.println((double)totalCount / pageSize);
	}

	@Override
	public boolean checkName(String name) {
		return studentDao.checkName(name);
	}
}
